﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Data;
using System.Windows.Controls;
using System.Windows.Navigation;
using System.ServiceModel.DomainServices.Client.ApplicationServices;
using System.ServiceModel.DomainServices.Client;
using System.Windows.Media;
using System.Xml.Linq;
using System.Text.RegularExpressions;
using TheCollectiveNetwork.Web.Services;
using TheCollectiveNetwork.Classes.Security;
using TheCollectiveNetwork.Views;
using TheCollectiveNetwork.CustomControls;
using TheCollectiveNetwork.Classes.GlobalConstantsVariables;
using TheCollectiveNetwork.Classes.GlobalFunctions;
using TCNDataAccessLayer;

namespace TheCollectiveNetwork.CustomControls
{
    public partial class MainPasswordChangeControl : UserControl
    { 
        // Define events and delegates
        public delegate void OnCloseControl(object sender, EventArgs e);
        public event OnCloseControl CloseControl;

        private UserCredentialContext _ucc;

        public MainPasswordChangeControl()
        {
            InitializeComponent();
           
        }

        public void LoadControl()
        {
            // Create a new context object
            _ucc = new UserCredentialContext();
            
            // Load the user name
            PasswordChangeControlUserNameText.Text = TCNauthentication.UserID;

            // Ensure password fields are blank
            PasswordChangeControlPasswordOldText.Password = String.Empty;
            PasswordChangeControlPasswordNewText.Password = String.Empty;
            PasswordChangeControlPasswordConfirmText.Password = String.Empty;
        }

        private void PasswordChangeControlCloseButton_Click(object sender, EventArgs e)
        {

            //Log the user out
            if (CloseControl != null)
            {
                CloseControl(this, null);
            }
        }


        private void PasswordChangeControlSaveButton_Click(object sender, EventArgs e)
        {
            string filteredpasswordold;
            string filteredpasswordnew;
            string filteredpasswordconfirm;
            bool errorfound = false;
            InvokeOperation iop;
            System.Windows.Documents.Run TextRun;
            SolidColorBrush scb_red;
            
            // Initialise variables
            scb_red = new SolidColorBrush(Colors.Red);

            // Strip out unwanted characters
            filteredpasswordold = Regex.Replace(strfunc.Left(PasswordChangeControlPasswordOldText.Password, 255), "[^0-9a-z'\"~@_\\-\\.]", string.Empty, RegexOptions.IgnoreCase);
            filteredpasswordnew = Regex.Replace(strfunc.Left(PasswordChangeControlPasswordNewText.Password, 255), "[^0-9a-z'\"~@_\\-\\.]", string.Empty, RegexOptions.IgnoreCase);
            filteredpasswordconfirm = Regex.Replace(strfunc.Left(PasswordChangeControlPasswordConfirmText.Password, 255), "[^0-9a-z'\"~@_\\-\\.]", string.Empty, RegexOptions.IgnoreCase);
            
            // Validate input
            if (filteredpasswordnew != PasswordChangeControlPasswordNewText.Password)
            {
                // Detect unusual characters                
                PasswordChangeControlMessageText.Text = "Error, please only use characters or numbers.";
                PasswordChangeControlErrorBorder.Visibility = System.Windows.Visibility.Visible;
                errorfound = true;
            }           
            else if (filteredpasswordnew != filteredpasswordconfirm)
            {
                // Detect zero length strings
                PasswordChangeControlMessageText.Text = "New password and re-type new password fields are different.";
                PasswordChangeControlErrorBorder.Visibility = System.Windows.Visibility.Visible;
                errorfound = true;
            }

            // Only proceed if no errors found.
            if (errorfound == false)
            {
                // Reset the error display               
                PasswordChangeControlMessageText.Text = String.Empty;
                PasswordChangeControlErrorBorder.Visibility = System.Windows.Visibility.Collapsed;
                PasswordChangeControlSaveButton.IsEnabled = false;

                // Start the busy indicator popup
                ProcessingIndicator.DisplayApplicationBusy();

                // Do the login                
                iop = _ucc.ChangePassword(filteredpasswordold, filteredpasswordnew);

                iop.Completed += (s, ea) =>
               {
                   if (iop.HasError == false)
                   {
                       PasswordChangeControlSaveButton.IsEnabled = true;
                   }
                   else
                   {
                       // Write error message            
                       TextRun = new System.Windows.Documents.Run();
                       TextRun.Text = iop.Error.Message;                                              
                       PasswordChangeControlMessageText.HorizontalAlignment = HorizontalAlignment.Center;
                       PasswordChangeControlMessageText.Inlines.Add(TextRun);
                       PasswordChangeControlErrorBorder.Visibility = System.Windows.Visibility.Visible;

                       PasswordChangeControlSaveButton.IsEnabled = true;

                       //Mark the error as handled
                       iop.MarkErrorAsHandled();
                   }

                   // Hide the app busy indicator
                   ProcessingIndicator.HideApplicationBusy();
               };

            }
           
        }

               

    }
}
